package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Resource
    private CategoryBrandService categoryBrandService;

    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    @Override
    public List<BrandDTO> queryBrandListByIds(List<Long> ids) {

        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
//        第一种方法
//        IPage<Brand> iPage = new Page<>(page,rows);
//        //动态sql，只有condition为true，自定义查询才会生效
//        boolean condition = StringUtils.isNotBlank(key);
//        //自动进行数据回填，当前页数据，总元素个数，总页数
//        this.page(iPage,new QueryWrapper<Brand>()
//       -         .like(condition,"name",key)
//                .or()
//                .eq(condition,"letter",key)
//        );
//        //分页查询结果封装，封装到pageDTO中
//        return new PageDTO<BrandDTO>(iPage.getTotal(),iPage.getPages(),BrandDTO.convertEntityList(iPage.getRecords()));

        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNotBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        this.query().like(isKeyExists,"name",key)
                .or()
                .eq(isKeyExists,"letter",key)
                .page(info);
        // 5.封装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(),info.getPages(),BrandDTO.convertEntityList(list));
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {

        // TODO   stream方式   //类::实例方法名 获取类里面的一个实例    实例对象->另外一个实例对象 转化为新的
        // 1.根据分类id，查询中间表，得到中间表对象集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("category_id", id).list();
        // 2.获取品牌id集合
        List<Long> brandIdList = categoryBrandList
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        // 3.根据品牌id集合，查询品牌对象集合
        return BrandDTO.convertEntityList(this.listByIds(brandIdList));
        //通过baseMapper实现
        //return this.baseMapper.queryBrandByCategoryId(id);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //将DTO转成po
        Brand brand = brandDTO.toEntity(Brand.class);
        //添加/修改品牌（有无id）
        this.saveOrUpdate(brand);
        //TODO 维护品牌和分类中间表
        //2.删除关系表
        categoryBrandService.deleteByBrandId(brand.getId());
        //获取分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 3.封装中间表对象集合
        List<CategoryBrand> categoryBrandList = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brand.getId());
            categoryBrandList.add(categoryBrand);
        }
//        // 封装中间表对象的集合   Lamda表达式
//        List<CategoryBrand> categoryBrandLists = brandDTO.getCategoryIds()
//                .stream()
//                .map(id -> CategoryBrand.of(id, brand.getId()))
//                .collect(Collectors.toList());
        //批量保存
        categoryBrandService.saveBatch(categoryBrandList);
    }

    @Override
    public void updateBrand(BrandDTO brandDTO) {

    }

    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        // 删除品牌表
        this.removeById(id);
        // TODO 删除中间表
        categoryBrandService.deleteByBrandId(id);
    }
}
